/**
*****************************************************************************
 * DESC ：. 
 * Author : Junwei Zhang 
 * CREATEDATE ：2012-8-28 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-8-28		Created.
 ****************************************************************************
**/
package com.me.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * 
 * <br/> 下午6:40:37 2012-8-28
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class ClientMe {
	
	public static void main(String[] args) throws IOException {
		new ClientMe().start();
	}

	private void start() throws IOException {
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		sc.connect(new InetSocketAddress("127.0.0.1", 8001));
		Selector selector = Selector.open();
		sc.register(selector, SelectionKey.OP_CONNECT);
		Scanner scanner = new Scanner(System.in);
		while(true){
			selector.select();
			Set<SelectionKey> keySet = selector.selectedKeys();
			System.out.println("keys=" + keySet.size());
			Iterator<SelectionKey> keyIterator = keySet.iterator();
			while(keyIterator.hasNext()){
				SelectionKey key = keyIterator.next();
				keyIterator.remove();
				if(key.isConnectable()){
					sc.finishConnect();
					sc.register(selector, SelectionKey.OP_WRITE);
					System.out.println("server connected...");
					break;
				}else if(key.isWritable()){
					System.out.println("please input message");
					String message = scanner.nextLine();
					ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes());
					sc.write(writeBuffer);
				}
			}
		}
	}
	
}
